package com.jtx.miaoah2.Utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtil {
    private static HttpClient httpClient = HttpClientBuilder.create().build();

    // 发送 GET 请求
    public static String sendGetRequest(String url) throws IOException {
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            return EntityUtils.toString(entity);
        }

        return null;
    }

    // 发送 POST 请求
    public static String sendPostRequest(String url, String requestBody) throws IOException {
        HttpPost request = new HttpPost(url);
        request.addHeader("Content-Type", "application/json");
        request.setEntity(new StringEntity(requestBody));

        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            return EntityUtils.toString(entity);
        }

        return null;
    }

    public static void main(String[] args) {
        String getUrl = "https://api.example.com/get";
        String postUrl = "https://api.example.com/post";
        String requestBody = "{\"key\": \"value\"}";

        try {
            // 发送 GET 请求并输出响应结果
            String getResult = sendGetRequest(getUrl);
            System.out.println("GET 请求结果：" + getResult);

            // 发送 POST 请求并输出响应结果
            String postResult = sendPostRequest(postUrl, requestBody);
            System.out.println("POST 请求结果：" + postResult);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
